const Goods = require('../model/goods.model')

class GoodsService {
  async createGoods(good) {
    const res = await Goods.create(good)
    return res.dataValues
  }

  async updateGoods(id, good) {
    const res = await Goods.update(good, { where: { id } })
    return res[0] > 0 ? true : false
  }

  async removeGoods(id) {
    const res = await Goods.destroy({ where: { id } })
    // console.log(res)
    return res > 0 ? true : false
  }

  async restoreGoods(id) {
    const res = await Goods.restore({ where: { id } })
    // console.log(res)
    return res > 0 ? true : false
  }

  async findOneGood(id) {
    const res = await Goods.findOne({ where: { id } })
    return res ? res.dataValues : null
  }

  async findGoods(pageNum, pageSize) {
    const offset = (pageNum - 1) * pageSize

    // 1.获取总数
    // const count = await Goods.count()
    // 2.获取分页的数据
    // const rows = await Goods.findAll({ offset, limit: pageSize * 1 })

    // 整合以上两个api
    const { count, rows } = await Goods.findAndCountAll({
      offset,
      limit: pageSize * 1,
    })

    return {
      pageNum,
      pageSize,
      total: count,
      rows,
    }
  }
}

module.exports = new GoodsService()
